package com.xingshi.springbootinit.aop;


import com.xingshi.springbootinit.common.ErrorCode;
import com.xingshi.springbootinit.exception.BusinessException;
import com.xingshi.springbootinit.model.entity.User;
import com.xingshi.springbootinit.service.ScoreService;
import com.xingshi.springbootinit.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 请求响应日志 AOP
 * @author 程序员苏打水
 **/
@Aspect
@Component
@Slf4j
public class ScoreInterceptor {
    @Resource
    private UserService userService;

    @Resource
    private ScoreService scoreService;

    /**
     * 执行拦截
     */
    @Around("@annotation(com.xingshi.springbootinit.annotation.ScoreReturn)")
    public Object doInterceptor(ProceedingJoinPoint point) throws Throwable {
        // 执行原方法
        Object result;
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        // 当前登录用户
        User loginUser = userService.getLoginUser(request);
        try {
            //预扣积分
            scoreService.deductScores(loginUser.getId(),1L);
            // 执行原方法
            result = point.proceed();
        }catch (BusinessException businessException){
            //出现异常则返还积分，生成失败不返还积分，提供重试（机制待完善）
            scoreService.returnScores(loginUser.getId(),1L);
            throw businessException;
        }
        return result;
    }
}
